package com.atguigu.team.service;

import com.atguigu.team.domain.Architect;
import com.atguigu.team.domain.Designer;
import com.atguigu.team.domain.Employee;
import com.atguigu.team.domain.Programmer;
 
public class TeamService {
	
	private static int counter = 1;
	
	public final int MAX_MEMBER = 6;
	private Programmer[] team = new Programmer[MAX_MEMBER];
	private int realCount = 0;
	
	/**
	 * 添加一个员工对象到团队中
	 * @param emp
	 * @throws TeamException 因某种原因失败
	 */
	public void addMember(Employee emp) throws TeamException {
		if (realCount == team.length) {
			throw new TeamException("成员已满，无法添加");
		}
		if (!(emp instanceof Programmer)) {
			throw new TeamException("添加的成员不是开发人员"); // 提前错误返回
		}
		Programmer programmer = (Programmer)emp;
		if (programmer.getMemberId() != 0) {
			throw new TeamException("该员已是团队成员");
		}
		if (programmer.getStatus() == Status.VOCATION) {
			throw new TeamException("该员正在休假，无法添加");
		}
		int architectCount = 0;
		int designerCount = 0;
		int programmerCount = 0;
		for (int i = 0; i < realCount; i++) {
			if (team[i] instanceof Architect) {
				architectCount++;
			} else if (team[i] instanceof Designer) {
				designerCount++;
			} else {
				programmerCount++;
			}
		}
		// 对将要添加的新成员的身份作一个判断
		if (programmer instanceof Architect) {
			if (architectCount == 1) {
				throw new TeamException("团队中只能有一名架构师");
			}
		} else if (programmer instanceof Designer) {
			if (designerCount == 2) {
				throw new TeamException("团队中只能有两名设计师");
			}
		} else {
			if (programmerCount == 3) {
				throw new TeamException("团队中只能有三名程序员");
			}
		}
		
		programmer.setMemberId(counter++); // 为要添加的新成员赋予一个团队ID号
		programmer.setStatus(Status.BUSY); // 修改对象的状态为busy
		team[realCount++] = programmer;
	}
	
	/**
	 * 获取所有团队成员的数组
	 * @return 完美数组
	 */
	public Programmer[] getTeam() {
		// 创建一个临时数组
		Programmer[] tmp = new Programmer[realCount];
		// 挨个复制所有有效元素
		for (int i = 0; i < tmp.length; i++) {
			tmp[i] = team[i];
		}
		// 返回临时数组
		return tmp;
	}
	
	/**
	 * 删除指定TID的团队成员
	 * @param memberId
	 * @throws TeamException
	 */
	public void removeMember(int memberId) throws TeamException {
		// 先根据memberId定位要删除的成员的下标
		int index = -1; // 先假定要删除的TID成员的下标不存在
		for (int i = 0; i < realCount; i++) {
			if (team[i].getMemberId() == memberId) {
				index = i;
				break;
			}
		}
		if (index == -1) { // 检索完成后, 再次检测下标是否有效, 如果无效说明没有找到
			throw new TeamException("要删除的TID[" + memberId + "]的团队成员未找到!");
		}
		// 在覆盖要删除的对象前进行对象的数据修改
		team[index].setMemberId(0); // 剥夺ID
		team[index].setStatus(Status.FREE); // 还原状态
		
		// 从要删除的下标开始,依次把右边的元素移到左边
		for (int j = index; j < realCount - 1; j++) {
			team[j] = team[j + 1];
		}
		// 把最后一个有效元素置为空洞
		// 调整计数器
		team[--realCount] = null;
	}
	
}
